<?php


namespace plugin\coleopenapi\exception;


use support\constants\RespCode;
use support\exception\BadException;
use Throwable;
use Webman\Exception\ExceptionHandler;
use Webman\Http\Request;
use Webman\Http\Response;
use Wengg\WebmanApiSign\ApiSignException;

class OpenApiExceptionHandler extends ExceptionHandler
{
    public $dontReport = [
        BadException::class,
        OpenApiException::class,
        ApiSignException::class,
    ];

    public function render(Request $request, Throwable $exception): Response
    {
        if (($exception instanceof BadException) && ($response = $exception->render($request))) {
            return $response;
        }
        if ($exception instanceof ApiSignException
            || $exception instanceof OpenApiException) {
            $code = $exception->getCode();
            $msg = $exception->getMessage();
            $data = [
                'message' => $msg ?: "操作失败!!!",
                'code' => $code ?: RespCode::ERROR,
                'data' => [],
            ];
            if ($request_id = request()->request_id) {
                $data['request_id'] = $request_id;
            }
            return json($data);
        }

        $code = $exception->getCode();
        if ($request->expectsJson()) {
            $json = ['code' => $code ?: 500, 'msg' => $this->debug ? $exception->getMessage() : 'Server internal error'];
            $this->debug && $json['traces'] = explode("\n", $exception);
            return new Response(200, ['Content-Type' => 'application/json'],
                json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        }
        $error = $this->debug ? nl2br((string)$exception) : 'Server internal error';
        return new Response(500, [], $error);
    }

}